package com.reservation.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.FileCopyUtils;

import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据库初始化配置，用于执行数据库事件脚本
 */
@Configuration
@Slf4j
public class DatabaseInitConfig implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化数据库事件调度");
        try {
            // 读取SQL脚本文件内容
            ClassPathResource resource = new ClassPathResource("db/automation/booking_timeout_event.sql");
            String script = FileCopyUtils.copyToString(
                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
            );

            // 按照特定模式分割SQL语句
            List<String> statements = extractSQLStatements(script);

            // 执行每条SQL语句
            for (String statement : statements) {
                if (!statement.trim().isEmpty()) {
                    log.debug("执行SQL: {}", statement);
                    try {
                        // 对于含有BEGIN...END的语句，需要特殊处理
                        if (statement.contains("BEGIN") && statement.contains("END")) {
                            // 直接执行整个事件创建语句
                            jdbcTemplate.execute(statement);
                        } else {
                            jdbcTemplate.execute(statement);
                        }
                    } catch (Exception e) {
                        // 某些语句可能会失败，例如检查事件状态的语句，这里我们记录但不中断执行
                        log.warn("SQL执行异常: {}", e.getMessage());
                    }
                }
            }

            log.info("数据库事件调度初始化完成");
        } catch (Exception e) {
            log.error("初始化数据库事件调度失败", e);
            throw e;
        }
    }

    /**
     * 提取SQL语句，特殊处理事件定义语句
     */
    private List<String> extractSQLStatements(String script) {
        List<String> statements = new ArrayList<>();

        // 正则表达式匹配CREATE EVENT语句(包括BEGIN...END块)
        Pattern eventPattern = Pattern.compile(
                "CREATE\\s+EVENT\\s+\\w+\\s+ON\\s+SCHEDULE.*?END;",
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE
        );

        Matcher matcher = eventPattern.matcher(script);
        int lastEnd = 0;

        // 先提取事件定义块
        while (matcher.find()) {
            // 添加事件块之前的语句
            String beforeEvent = script.substring(lastEnd, matcher.start());
            Arrays.stream(beforeEvent.split(";"))
                  .map(String::trim)
                  .filter(s -> !s.isEmpty())
                  .forEach(s -> statements.add(s + ";"));

            // 添加完整的事件定义块
            statements.add(matcher.group());
            lastEnd = matcher.end();
        }

        // 添加剩余的语句
        if (lastEnd < script.length()) {
            String remaining = script.substring(lastEnd);
            Arrays.stream(remaining.split(";"))
                  .map(String::trim)
                  .filter(s -> !s.isEmpty())
                  .forEach(s -> statements.add(s + ";"));
        }

        return statements;
    }




}